package com.backend.service.rbac.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.backend.mapper.rbac.AuthMapper;
import com.backend.service.rbac.AuthService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.exception.AuthException;
import com.pojo.dto.AuthDTO;
import com.pojo.entity.Auth;
import com.pojo.vo.AuthVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AuthServiceImpl extends ServiceImpl<AuthMapper, Auth> implements AuthService {
    @Autowired
    AuthMapper authMapper;
    @Override
    public void insertAuth(AuthDTO authDTO) {
        Auth auth = BeanUtil.copyProperties(authDTO, Auth.class);
        auth.setCreateDatetime(LocalDateTime.now());
        auth.setUpdateDatetime(LocalDateTime.now());
        auth.setStatus(0);
        save(auth);
    }

    @Override
    public Integer removeAuth(String name) {
        return authMapper.removeAuth(name);
    }

    @Override
    public Integer updateAuth(AuthDTO authDTO) {
        LocalDateTime now = LocalDateTime.now();
        Auth auth = getById(authDTO.getId());
        auth.setUpdateDatetime(now);
        if (StrUtil.isNotBlank(authDTO.getName())) {
            auth.setName(authDTO.getName());
        }
        if (StrUtil.isNotBlank(authDTO.getPermission())) {
            auth.setPermission(authDTO.getPermission());
        }
        return authMapper.updateById(auth);
    }

    @Override
    public List<AuthVO> getAllAuth() {
        List<Auth> auths = authMapper.getAllAuth();
        List<AuthVO> authVOS = auths.stream().map(auth -> {
            return BeanUtil.copyProperties(auth, AuthVO.class);
        }).collect(Collectors.toList());
        return authVOS;
    }

    @Override
    public AuthVO getAuthByName(String name) {
        Auth auth = authMapper.getAuthByName(name);
        if (auth == null) {
            throw new AuthException("无该权限");
        }
        AuthVO authVO = BeanUtil.copyProperties(auth, AuthVO.class);
        return authVO;
    }

    @Override
    public Integer updateAuthStatus(Long id, Integer status) {
        Auth auth = getById(id);
        auth.setStatus(status);
        auth.setUpdateDatetime(LocalDateTime.now());
        Integer result = authMapper.updateById(auth);
        return result;
    }
}
